package com.wangxin.study8.completablefuture;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName CompletionServiceTest
 * @Description TODO
 * @Author jojo.wang
 * @Date 2019-05-30 23:03
 * @Version 1.0
 **/
public class CompletionServiceTest {
    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletionService<Integer> cs = new ExecutorCompletionService<>(executorService);
        List<Future<Integer>> futures = new ArrayList<>();
        futures.add(cs.submit(()->{
            Thread.sleep(10);
            return 1;
        }));
        futures.add(cs.submit(()->{
            Thread.sleep(20);
            return 2;
        }));

        futures.add(cs.submit(()->{
            Thread.sleep(30);
            return 3;
        }));
        
        Integer r = null;
        try {
            for (int i = 0; i < 3; i++) {
                r = cs.take().get();
                if (null!=r){
                    break;
                }
            }
        }finally {
            for (Future<Integer> future : futures) {
                future.cancel(true);
            }
        }

        System.out.println(r);
        executorService.shutdown();

    }
}
